{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "请根据问题三中建立\n",
    "的模型预测第 10 个月该车辆可能会出现的故障报警时刻（填写“month_10.csv”\n",
    "文件中的时间点即可）及报警等级（示表中只需要填写故障等级 1-3 的情况），\n",
    "并将预测结果展示在报告中。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "device(type='cuda')"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import os\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "import matplotlib.pyplot as plt\n",
    "import matplotlib\n",
    "import torch\n",
    "from sklearn.preprocessing import MinMaxScaler\n",
    "from torch.utils.data import DataLoader, TensorDataset\n",
    "import config\n",
    "import torch.nn as nn\n",
    "matplotlib.rcParams['font.family'] = 'SimHei'  # 例如使用黑体\n",
    "matplotlib.rcParams['font.sans-serif'] = ['SimHei']\n",
    "plt.rcParams['axes.unicode_minus'] = False  # 解决负号显示问题\n",
    "torch.cuda.is_available()\n",
    "device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n",
    "os.environ['CUDA_LAUNCH_BLOCKING'] = '1'\n",
    "device"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 加载数据"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [],
   "source": [
    "data = pd.read_csv('./processed_data/month10_cleaned.csv')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 数据预处理"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [],
   "source": [
    "from utils import change_df_sec\n",
    "# 如果还未转换，则进行转换\n",
    "data['数据采集时间'] = change_df_sec(data['数据采集时间'])\n",
    "# 更新 X 以包含转换后的时间数据\n",
    "# 去掉数据采集时间。因为我们已经有了时间步长\n",
    "X = data.drop(['最高报警等级'], axis=1)\n",
    "y = data['最高报警等级']\n",
    "X = X.values\n",
    "y = y.values\n",
    "batch_size = config.BATCH_SIZE\n",
    "input_size = X.shape[1]\n",
    "output_size = 1\n",
    "hidden_size = 64\n",
    "num_layers = 2\n",
    "num_classes = 4"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [],
   "source": [
    "from utils import create_time_seq\n",
    "# 标准化数据\n",
    "scaler = MinMaxScaler()\n",
    "X_scaled = scaler.fit_transform(X)\n",
    "\n",
    "sequences, labels = create_time_seq(X_scaled, y)\n",
    "\n",
    "X_seq = np.array(sequences)\n",
    "y_seq = np.array(labels)\n",
    "\n",
    "# 转换为 PyTorch 张量并移到 GPU\n",
    "X = torch.tensor(X_seq, dtype=torch.float32).to(device)\n",
    "y = torch.tensor(y_seq, dtype=torch.long).to(device)\n",
    "\n",
    "# 创建数据加载器\n",
    "dataset = TensorDataset(X, y)\n",
    "\n",
    "data_loader = DataLoader(dataset, batch_size=batch_size)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## LSTMCNN模型"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [],
   "source": [
    "from model import *"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 预测"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [],
   "source": [
    "model = torch.load('./model/lstm_cnn_last.pth')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 在测试集上评估模型\n",
    "model.eval()\n",
    "all_preds = []\n",
    "all_labels = []\n",
    "\n",
    "with torch.no_grad():\n",
    "    for X_batch, y_batch in data_loader:\n",
    "        outputs = model(X_batch)\n",
    "        _, predicted = torch.max(outputs.data, 1)\n",
    "        all_preds.extend(predicted.cpu().numpy())\n",
    "        all_labels.extend(y_batch.cpu().numpy())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(1349, 1349, 1349)"
      ]
     },
     "execution_count": 21,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "len(all_preds), len(all_labels), len(data)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [],
   "source": [
    "data['最高报警等级'] = all_preds"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [],
   "source": [
    "origin_data = pd.read_csv('./data/month_10.csv', encoding='gb2312')\n",
    "origin_data = origin_data.sort_values(by='数据采集时间')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {},
   "outputs": [],
   "source": [
    "ret = pd.DataFrame()\n",
    "ret['数据采集时间'] = origin_data['数据采集时间']\n",
    "ret['最高报警等级'] = data['最高报警等级']\n",
    "ret.to_excel('./data/result.xlsx', index=False)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Pytorch",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.16"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
